import { Util, Loading } from '@/ibiz-core/utils';
import UIActionBase from '@/utils/ui-service-base/ui-action-base';
import { ViewOpenService } from '@/utils/view-open-service/view-open-service';

/**
 * 全局界面行为基类
 *
 * @export
 * @class GlobalUiServiceBase
 * @extends {UIActionBase}
 */
export default class GlobalUiServiceBase extends UIActionBase {

    /**
     * Creates an instance of UiServiceBase.
     * 
     * @memberof UiServiceBase
     */
    constructor() {
        super();
    }


    /**
     * 保存并关闭
     *
     * @param {any[]} args 数据
     * @param {*} [contextJO={}] 行为上下文
     * @param {*} [paramJO={}] 行为参数
     * @param {*} [$event] 事件
     * @param {*} [xData] 数据目标
     * @param {*} [container] 行为容器对象
     * @param {string} [srfParentDeName]
     * @returns {Promise<any>}
     * @memberof 
     */
    public async SaveAndExit(args: any[], contextJO: any = {}, paramJO: any = {}, $event?: any, xData?: any, container?: any, srfParentDeName?: string): Promise<any> {
        let response: any;
        if (xData && xData.saveAndExit instanceof Function) {
            const _data = {};
            response = await xData.saveAndExit(_data);
            if (response || response.status === 200) {
                container.$emit('viewdataschange', [{ ...response.data }]);
            }
        } else if (container.saveAndExit && container.saveAndExit instanceof Function) {
            response = await xData.saveAndExit();
            if (response || response.status === 200) {
                container.$emit('closeview', [{ ...response.data }]);
            }
        }
        return response;
    }

    /**
     * 开始流程
     *
     * @param {any[]} args 数据
     * @param {*} [contextJO={}] 行为上下文
     * @param {*} [paramJO={}] 行为参数
     * @param {*} [$event] 事件
     * @param {*} [xData] 数据目标
     * @param {*} [container] 行为容器对象
     * @param {string} [srfParentDeName]
     * @returns {Promise<any>}
     * @memberof 
     */
    public async SaveAndStart(args: any[], contextJO: any = {}, paramJO: any = {}, $event?: any, xData?: any, container?: any, srfParentDeName?: string): Promise<any> {
        const that: any = container;
        if (!xData || !(xData.wfstart instanceof Function) || !(that.appEntityService)) {
            return;
        }
        let validateStatus: boolean = true;
        if (xData.validAll instanceof Function) {
            validateStatus = await xData.validAll();
        }
        if (!validateStatus) {
            that.$notice.error('值规则校验异常');
            return;
        }
        const startWorkFlow: Function = (param: any, localdata: any) => {
            xData.wfstart(param, localdata).then((response: any) => {
                if (!response || response.status !== 200) {
                    return;
                }
                const { data: _data } = response;
                that.closeView(_data);
            });
        }
        const openStartView: Function = async (item: any, localdata: any) => {
            if (item['wfversion']) {
                const targetView: any = that.viewRefData ? that.viewRefData[`WFSTART@${item['wfversion']}`] : null;
                if (targetView) {
                    const tempContext = Util.deepCopy(that.context);
                    const tempViewParams = { actionView: `WFSTART@${item['wfversion']}`, actionForm: item['process-form'] };
                    ViewOpenService.getInstance().openModal(targetView, tempContext, tempViewParams).then((result: any) => {
                        if (!result || !Object.is(result.ret, 'OK')) {
                            return;
                        }
                        const tempSubmitData: any = Util.deepCopy(args[0]);
                        if (result.datas && result.datas[0]) {
                            const resultData: any = result.datas[0];
                            if (Object.keys(resultData).length > 0) {
                                let tempData: any = {};
                                Object.keys(resultData).forEach((key: any) => {
                                    if (resultData[key] || (resultData[key] === 0) || (resultData[key] === false)) {
                                        tempData[key] = resultData[key];
                                    }
                                })
                                Object.assign(tempSubmitData, tempData);
                            }
                        }
                        startWorkFlow([tempSubmitData], localdata);
                    })
                } else {
                    startWorkFlow(args, localdata);
                }
            } else {
                startWorkFlow(args, localdata);
            }
        }
        let localData: any;
        const localContext = Util.deepCopy(that.context);
        const requestResult: Promise<any> = that.appEntityService.getStandWorkflow(localContext);
        requestResult.then((response: any) => {
            const { data: targetData, status } = response;
            if (status !== 200 || targetData.length === 0) {
                return;
            }
            if (targetData && targetData.length > 1) {
                const h = that.$createElement;
                const msgBoxContent = h('app-wfversion-select', {
                    props: {
                        versionItems: targetData,
                        majorKey: 'definitionkey',
                        versionTitle: 'definitionname'
                    },
                    on: {
                        valueChange: (value: any) => {
                            localData = { processDefinitionKey: value };
                        }
                    }
                });
                ViewOpenService.getInstance().openMsgBox({
                    type: 'info',
                    title: '请选择流程版本',
                    showCancelButton: true,
                    content: msgBoxContent
                }).then((result: boolean) => {
                    if (result === true) {
                        const targetItem = targetData.find((item: any) => {
                            return item.definitionkey === localData.processDefinitionKey;
                        })
                        openStartView(targetItem, localData);
                    }
                })
            } else {
                localData = { processDefinitionKey: targetData[0]['definitionkey'] }
                targetData[0]['process-view'] = "WFSTART@1";
                openStartView(targetData[0], localData);
            }
        })
    }


    /**
     * 新建
     *
     * @param {any[]} args 数据
     * @param {*} [contextJO={}] 行为上下文
     * @param {*} [paramJO={}] 行为参数
     * @param {*} [$event] 事件
     * @param {*} [xData] 数据目标
     * @param {*} [container] 行为容器对象
     * @param {string} [srfParentDeName]
     * @returns {Promise<any>}
     * @memberof 
     */
    public async New(args: any[], contextJO: any = {}, paramJO: any = {}, $event?: any, xData?: any, container?: any, srfParentDeName?: string): Promise<any> {
         const _this: any = this;
        if (container.newdata && container.newdata instanceof Function) {
            const data: any = {};
            container.newdata(args, contextJO, paramJO, $event, xData, container, srfParentDeName);
        } else {
            this.notice.error('newdata 视图处理逻辑不存在，请添加!');
        }
    }
}